from django.contrib.auth import authenticate, login, logout

verification_code = {}


def try_login(request, qq, code):
    if qq in verification_code and verification_code[qq] == code:
        # 登录用户
        user = authenticate(request, username=qq, code=code)
        if user is not None:
            login(request, user)
            return True
    return False


def try_logout(request, qq):
    if qq in verification_code:
        del verification_code[qq]
    logout(request)
    return True


def quick_login(func):
    def wrapper(request):
        qq = request.GET.get('qq')
        code = request.GET.get('code')
        if qq and code:
            try_login(request, qq, code)
        return func(request)

    return wrapper
